﻿using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using QuoteTree;
using System.IO;
using EB;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;


public partial class Private_TreeView : System.Web.UI.Page
{
    protected void Page_Load(object sender, System.EventArgs e)
    {

        if (Session.IsNewSession)
        {
            // If it says it is a new session, but an existing cookie exists, then it must 
            // have timed out (can't use the cookie collection because even on first 
            // request it already contains the cookie (request and response
            // seem to share the collection)
            string szCookieHeader = Request.Headers["Cookie"];
            if ((null != szCookieHeader) && (szCookieHeader.IndexOf("ASP.NET_SessionId") >= 0))
            {
                Response.Redirect("sessionTimeout.aspx");
            }
        }

        if (!IsPostBack)
        {
            //Remove previous tree
            this.Session["tree"] = null;
            this.Session["leftframe"] = null;
            this.HyperLink6.Target = "details";


            if (this.Request.QueryString["quote"] != null)
            {
                this.HyperLink6.NavigateUrl = "QuoteTreeDetails.aspx?quote=" + this.Request.QueryString["quote"].ToString();

                //Show the product tree in the TreeView from the databasse
                this.ShowTreeViewFromDatabase();
            }
            else if (this.Request.QueryString["product"] != null)
            {
                this.HyperLink6.NavigateUrl = "QuoteTreeDetails.aspx";

                //Show the product tree in the TreeView from the session
                this.ShowTreeViewFromSession(this.Request.QueryString["product"].ToString());
            }

            //This is to show the quote when first visting the page
            if (this.Request.QueryString["quote"] != null)
            {
                this.DescriptionFrame.Attributes.Add("Src", this.HyperLink6.NavigateUrl);
                this.Session["leftframe"] = this.HyperLink6.NavigateUrl;
            }

            //If it is a revision disable the tree and other controls
            if (this.Request.QueryString["quote"] != null && this.Request.QueryString["quote"].ToString() != ""
                        && (this.Request.QueryString["revision"] == null || this.Request.QueryString["revision"] != "yes"))
            {
                this.TreeView1.Enabled = false;
                this.Button3.Visible = true;
            }
        }
    }

    #region Web Form Designer generated code
    override protected void OnInit(EventArgs e)
    {
        //
        // CODEGEN: This call is required by the ASP.NET Web Form Designer.
        //
        InitializeComponent();
        base.OnInit(e);
    }

    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {

    }
    #endregion

    public void FillTreeViewNode(INode node, TreeNode ui_node)
    {
        decimal o;
        if (node.hidden) return;
        if (node.parent != null && node.parent.parent != null && node.parent.parent.type == NodeType.decision && !node.parent.selected) return;
        if (node.parent != null && node.parent.type == NodeType.math && (node.parent as MathNode).edit_children &&
            decimal.TryParse((node as MathNode).formula, out o)) return;

        if (node.parent != null && node.parent.optional && !node.parent.selected) return;

        //If not selected and some brother is selected then not insert the node.
        bool some_selected = false;
        if (node.parent != null && node.parent.type == NodeType.decision && !node.selected)
        {
            foreach (INode n in node.parent.children)
                if (n.selected) some_selected = true;
            if (some_selected) return;
        }


        string name = node.name;

        TreeNode new_node = new TreeNode();

        //new_node.PopulateOnDemand = true;

        if (node.selected) new_node.Checked = true;

        if (node.checkbox) new_node.ShowCheckBox = true;

        if (node.expanded) new_node.Expanded = true;

        new_node.Text = name;
        new_node.Value = node.name;
        new_node.ToolTip = node.description;

        new_node.NavigateUrl = node.url;
        new_node.Target = "details";

        ui_node.ChildNodes.Add(new_node);
        if (node.children != null && node.children.Count != 0)
        {
            foreach (INode n in node.children)
            {
                FillTreeViewNode(n, new_node);
            }
        }
    }

    public void ShowTreeViewFromSession(string product)
    {
        this.TreeView1.Nodes.Clear();
        this.DescriptionFrame.Attributes.Add("src", "Quotes/" + product + "/homepage.htm");

        // Check if there's a tree cached in an application variable and set it as a session variable
        if (this.Application["allproducts"] != null)
        {
            ArrayList allproducts = this.Application["allproducts"] as ArrayList;
            foreach (QTree tree in allproducts)
            {
                if (tree.Root.name == product)
                {
                    //Free the memory
                    QTree delete = (this.Session["tree"] as QTree);
                    delete = null;
                    System.GC.Collect();
                    //Assign new tree
                    this.Session["tree"] = new QTree(tree);
                    break;
                }
            }
        }
        else
        {
            string s = Server.MapPath("~/Private/Quotes/" + product);
            this.Session["tree"] = new QTree(@s);
        }

        //Populate first level of the tree.
        TreeNode n1 = new TreeNode();
        n1.Text = (this.Session["tree"] as QTree).Root.name;
        n1.PopulateOnDemand = true;
        n1.Expanded = true;
        n1.NavigateUrl = (this.Session["tree"] as QTree).Root.url;


        this.TreeView1.Nodes.Clear();
        this.TreeView1.Nodes.AddAt(0, n1);

        this.Session["leftframe"] = null;

        this.Label1.Text = "Total = $0";
    }

    public void ShowTreeViewFromDatabase()
    {
        DataSet ds;
        string quote = this.Request.QueryString["quote"].ToString();
        BinaryFormatter formater = new BinaryFormatter();
        byte[] bytes_stream;

        ds = qman.DataHelp.DataAccess.getDataSet("select quote from quotes where id=" + this.Request.QueryString["quote"].ToString());
        bytes_stream = ds.Tables[0].Rows[0][0] as byte[];
        MemoryStream memory_stream = new MemoryStream(bytes_stream);
        QTree tree = (formater.Deserialize(memory_stream)) as QTree;
        this.Session["tree"] = tree;
        this.Label1.Text = "Total = $" + Decimal.Round(tree.Root.total(), 0);

        //Fill the TreeView with the session tree
        //Populate first level of the tree.
        TreeNode n1 = new TreeNode();
        n1.Text = (this.Session["tree"] as QTree).Root.name;
        n1.PopulateOnDemand = true;
        n1.Expanded = true;
        n1.NavigateUrl  = (this.Session["tree"] as QTree).Root.url;

        this.TreeView1.Nodes.Clear();
        this.TreeView1.Nodes.AddAt(0, n1);
    }

    protected void Button3_Click(object sender, EventArgs e)
    {
        this.TreeView1.Enabled = true;
        this.HyperLink6.Enabled = true;
        this.Button3.Visible = false;
        this.HyperLink6.NavigateUrl += "&revision=yes";
    }

    protected void TreeView1_TreeNodePopulate(object sender, TreeNodeEventArgs e)
    {
        QTree tree = this.Session["tree"] as QTree;
        INode current_node = tree.GetNodeFromPath(e.Node.ValuePath);//.Remove(0, 6));

        foreach (INode node in current_node.children)
        {
            if (!node.hidden)// || this.CheckBox3.Checked)  // && !(current_node.type == NodeType.decision && !node.selected ))
            {
                //Create a new tree node
                TreeNode new_node = new TreeNode(node.name);

                //Set new node attributes
                new_node.PopulateOnDemand = true;
                new_node.ShowCheckBox = node.checkbox;
                new_node.Checked = node.selected;
                new_node.NavigateUrl = node.url;
                new_node.Target = "details";

                //Insert new node in parent's children collection
                e.Node.ChildNodes.Add(new_node);
            }
        }
    }
}
